package org.com.lcuiot.handler;

import org.com.lcuiot.database.dto.IotData;
import org.com.lcuiot.service.AcceptDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @author gaoge
 * @since  2022/10/22 07:33
 */
@RestController
public class AcceptDataHandler {
    private static final Logger logger = LoggerFactory.getLogger(AcceptDataHandler.class);

    private final AcceptDataService acceptDataService;

    @Autowired
    public AcceptDataHandler(AcceptDataService acceptDataService) {
        this.acceptDataService = acceptDataService;
    }


    @Bean
    public RouterFunction<ServerResponse> acceptDataExampleRouter() {
        logger.info("Init Controller accept data");
        return route()
                .GET("/accept_data", this::acceptDataHandler)
                .POST("/accept_data", RequestPredicates.contentType(MediaType.APPLICATION_JSON), this::acceptPushDataHandler)
                .build();
    }

    private Mono<ServerResponse> acceptDataHandler(ServerRequest request) {
        String productId = request.queryParam("productId").orElse(null);
        String productInfo = "accept check request：产品ID：" + productId;
        logger.debug(productInfo);
        String msg = request.queryParam("msg").orElse(null);
        return ok().body(fromValue(msg));
    }

    private Mono<ServerResponse> acceptPushDataHandler(ServerRequest request) {
        String productId = request.queryParam("productId").orElse(null);
        String productInfo = "产品ID：" + productId + " 开始推送数据";
        logger.debug(productInfo);
        return request.bodyToMono(IotData.class)
                .flatMap(iotData -> Mono.just(acceptDataService.save2RedisStream(iotData)))
                .flatMap(iotData -> ServerResponse.ok().body(fromValue("succ")));

    }


}
